﻿using System;

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

namespace zframe.loader
{
    /// <summary>
    /// 自定义UnityWebRequest的下载处理器
    /// </summary>
    public class CustomerDownloadHandler:DownloadHandlerScript
    {
        public CustomerDownloadHandler():base() { }    
        public CustomerDownloadHandler(byte[] buffs) : base(buffs) {
        }

        private byte[] _buffers;   

        private ulong _contentLen = 0;

        /// <summary>
        /// 接收到内容总长度 用这个
        /// </summary>
        /// <param name="contentLength"></param>
        protected override void ReceiveContentLengthHeader(ulong contentLength)
        {
            _contentLen = contentLength;
            Debug.Log("CustomerDownloadHandler ReceiveContentLengthHeader contentLength=" + contentLength);
            base.ReceiveContentLengthHeader(contentLength);
        }

        protected override byte[] GetData()
        {
            return _buffers;
        }

        /// <summary>
        /// 接收到数据后 每帧调用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="dataLength"></param>
        /// <returns></returns>
        protected override bool ReceiveData(byte[] data, int dataLength)
        {
            if (data==null || dataLength<=0)
            {
                Debug.Log("CustomerDownloadHandler ReceiveData 接收到无效的数据..");
                return false;   
            }
            Debug.Log("CustomerDownloadHandler dataLength=" + dataLength+"="+ data.Length);
            var len = (ulong)dataLength;
            if (len == _contentLen)
            {
                _buffers = data;
            }
            return base.ReceiveData(data, dataLength);
        }
        protected override void CompleteContent()
        {
            Debug.Log("CustomerDownloadHandler 数据接收完成 this.data=" + this.data);
            base.CompleteContent();
        }

    }
}
